<?php
/**
 * H5支付
 */

namespace app\api\service\payment;


use app\api\service\ApiPayment;
use app\common\library\exception\OrderException;
use think\Log;

class H5pay extends ApiPayment
{
    public function alih5pay($order)
    {
        return $this->requestApi("http://27.124.8.30/Pay/GateWayAliPay.aspx", $order);
    }

    // public function wxh5pay($order)
    // {
    //     return $this->requestApi("http://27.124.8.30/Pay/GateWayTencent.aspx", $order);
    // }

    public function requestApi($url, $order)
    {
        $app_id  = $this->config['app_id'];
        $key = $this->config['app_key'];
        $pay_type = '2';

        $order_id = $order["trade_no"];
        $order_amt = bcmul($order['amount'], 1, 2); //转为高精度数字类型

        $goods_name = empty($order["subject"]) ? '' : urldecode($order["subject"]);

        $notify_url = 'http://111.231.76.48/notify/h5pay';
        $return_url = empty($order["return_url"]) ? '' : urldecode($order["return_url"]);

        $time_stamp = date("YmdHis", time());

        $sign = 'app_id=' . $app_id
            . '&pay_type=' . $pay_type
            . '&order_id=' . $order_id
            . '&order_amt=' . $order_amt
            . '&notify_url=' . $notify_url
            . '&return_url=' . $return_url
            . '&time_stamp=' . $time_stamp
            . '&key=' . md5($key);

        $data = array(
            'app_id' => $app_id,
            'pay_type' => $pay_type,
            'order_id' => $order_id,
            'order_amt' => $order_amt,
            'goods_name' => urlencode($goods_name),
            'notify_url' => urlencode($notify_url),
            'return_url' => urlencode($return_url),
            'time_stamp' => $time_stamp,
            'sign' => md5($sign)
        );

        $result              =  self::curl($url, $data); // 发起远程请求

        $res = json_decode($result);
        if ($res->status_code == 0) {
            return [
                'order_id' => $order['out_trade_no'],
                'pay_seq' => $order['trade_no'],
                'pay_url' => $res->pay_url,
            ];
        } else {
            throw new OrderException([
                'msg'   =>  $res->status_msg,
                'errCode'   =>  $res->status_code
            ]);
        }
    }

    public function notify()
    {
        return $this->verifyOrderNotify();
    }

    /**
     * 回调验签
     *
     *
     * @return array
     * @throws OrderException
     */
    private function verifyOrderNotify()
    {
        //@todo 校验签名
        return array(
            'trade_no' => \think\Request::instance()->param('order_id'),
            // 'amount' => \think\Request::instance()->param('pay_amt')
        );

        return true;
        libxml_disable_entity_loader(true);
        //Object  对象
        $response = json_decode(json_encode(simplexml_load_string(file_get_contents("php://input"), 'SimpleXMLElement', LIBXML_NOCDATA), JSON_UNESCAPED_UNICODE), true);
        //读订单对应的支付渠道配置
        $this->config = self::getOrderPayConfig($response['out_trade_no']);
        if (self::getWxpaySign($response, $this->config['mch_key']) !== $response['sign']) {
            Log::error('Verify WxOrder Notify Error');
            throw new OrderException([
                'msg'   => 'Verify WxOrder Notify Error',
                'errCode'   => 200010
            ]);
        }
        echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
    }

    private static function curl($url, $param)
    {
        $postdata = http_build_query($param);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）    
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }
}
